package com.chcit.mobile.mvp.receive.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chcit.custom.view.toolbar.CommonToolbar;
import com.chcit.custom.view.toolbar.TextViewOptions;
import com.chcit.mobile.app.base.ScanOrZxingFragment;
import com.chcit.mobile.app.base.ScanToolFragment;
import com.chcit.mobile.common.DataKeys;
import com.chcit.mobile.mvp.entity.HomeItem;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.material.textfield.TextInputLayout;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.loader.QuickLoader;
import com.xuexiang.xui.widget.spinner.editspinner.EditSpinner;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.di.component.DaggerScanPackageComponent;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.entity.Locator;
import com.chcit.mobile.mvp.entity.ReceiveBean;
import com.chcit.mobile.mvp.entity.Statu;
import com.chcit.mobile.mvp.common.adapter.PackageScanAdapter;
import com.chcit.mobile.mvp.common.contract.ScanPackageContract;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.chcit.mobile.mvp.common.presenter.ScanPackagePresenter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.edittext.ValidatorEditText;
import com.xuexiang.xui.widget.toast.XToast;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 入库扫码验收页面
 */
public class ReceiveScanPackageFragment extends ScanOrZxingFragment<ScanPackagePresenter> implements ScanPackageContract.View {

    @BindView(R.id.tiet_receive_scan_no)
    ValidatorEditText tietNo;

    @BindView(R.id.img_receive_scan)
    AppCompatImageView imgScan;
    @BindView(R.id.tv_receive_scan_productname)
    TextView tvProductname;
    @BindView(R.id.tv_receive_scan_lot)
    TextView tvLot;
    @BindView(R.id.tv_receive_scan_productSpec)
    TextView tvProductSpec;
    @BindView(R.id.tv_receive_scan_manufacturer)
    TextView tvManufacturer;
    @BindView(R.id.tv_receive_scan_receivePackageNum)
    TextView tvPackageNum;
    @BindView(R.id.lv_receive_scan_waitReceivePackageNum)
    TextView lvWaitPackageNum;
    @BindView(R.id.tv_receive_scan_waitReceivePackageNum)
    TextView tvWaitPackageNum; //待验收包数
    @BindView(R.id.tv_receive_scan_receiveNum)
    TextView tvReceiveNum;
    @BindView(R.id.lv_receive_scan_waitReceiveNum)
    TextView lvWaitReceiveNum;
    @BindView(R.id.tv_receive_scan_waitReceiveNum)
    TextView tvWaitReceiveNum;
    @BindView(R.id.lv_receive_scan_receivedPackageNum)
    TextView lvReceivedPackageNum;
    @BindView(R.id.tv_receive_scan_receivedPackageNum)
    TextView tvReceivedPackageNum;
    @BindView(R.id.tv_receive_scan_rejectedReceivePackageNum_label)
    TextView tvRejectedReceivePackageNumLabel;
    @BindView(R.id.tv_receive_scan_rejectedReceivePackageNum)
    TextView tvRejectedPackageNum;
    @BindView(R.id.lv_receive_scan_receivedNum)
    TextView lvReceivedNum;
    @BindView(R.id.tv_receive_scan_receivedNum)
    TextView tvReceivedNum;
    @BindView(R.id.tv_receive_scan_rejectedReceiveNum_label)
    TextView tvRejectedNumLabel;
    @BindView(R.id.tv_receive_scan_rejectedReceiveNum)
    TextView tvRejectedNum;
    @BindView(R.id.dr_receive_scan_locator)
    EditSpinner spinnerLocator;
    @BindView(R.id.tl_tabs)
    TabLayout tlTabs;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.rv_receive_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.nsv)
    NestedScrollView nsv;
    @BindView(R.id.bt_receive_scan_ok)
    Button btOk;
    @BindView(R.id.bt_receive_scan_kx)
    Button btKx;
    String page;
    BigDecimal waitReceiveNum;
    protected CommonToolbar mCommonToolbar ;
    private int position;
    private List<PackageBean> unPackageBeans;
    private List<PackageBean> donePackageBeans = new ArrayList<>();
    private PackageScanAdapter unScanAdapter;
    private PackageScanAdapter doneScanAdapter;
    private ReceiveBean mReceiveBean;
    private List<Locator> locators;
    private Locator locator;
    private MenuTypeEnum type;


    public static ReceiveScanPackageFragment newInstance(ReceiveBean receiveBean, MenuTypeEnum type) {
        ReceiveScanPackageFragment fragment = new ReceiveScanPackageFragment();
        fragment.mReceiveBean = receiveBean;
        fragment.type = type;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerScanPackageComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_receive_scan_package, container, false);
        initToolBar(rootView);
        return rootView;
    }


    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        showTaskInfo();
        getData("N");
    }

    /**
     *
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        if (spinnerLocator.isFocused()) {
            spinnerLocator.setText(barcodeData);
            JSONObject params = new JSONObject();
            params.put("value", barcodeData);
            assert mPresenter != null;
            mPresenter.getLocators(params, list -> {
                locator = list.get(0);
            });
        } else {
            tietNo.setText(barcodeData);
            checkPackageNo(barcodeData);
        }
    }

    //操作
    @SuppressLint("SetTextI18n")
    private void showTaskInfo() {
        tvManufacturer.setText(mReceiveBean.getManufacturer());
        mCommonToolbar.setTitleText("包装扫码-" + type.getDesc());
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            if(doneScanAdapter.getData().size() > 0){
                new MaterialDialog.Builder(mContext)
                        .content("是否放弃本次操作！")
                        .positiveText("否")
                        .negativeText("是")
                        .onNegative((dialog, which) -> {
                            for(PackageBean p: doneScanAdapter.getData()){
                                packageBean = p;
                                mReceiveBean.setUnitQty(packageBean.getUnitPackQty().toString());
                                updateSubstractPackageInfo(BigDecimal.ONE);
                            }
                           backEvent();
                        }).show();
                return;
            }
            backEvent();
        });
        switch (type) {
            case PURCHASE_CHECK:
                page="check";
                btKx.setVisibility(View.VISIBLE);
                btKx.setOnClickListener( v->{
                    if (donePackageBeans.size() > 0) {
                        inspectePackageConfirm();
                    } else {
                        DialogUtil.showErrorDialog(mContext, "请扫码需要验收的包装！");
                    }
                });
                setViewTextReceive();
                break;
            case PURCHASE_RECEIVE:
                page="receive";
                setViewTextPickUp();
                break;
            case YN_CHECK:
                page = "check";
                setViewTextReceive();
                break;
            case YN_RECEIVE:
                page="receive";
                setViewTextPickUp();
                break;
            case REJECT:
                page="rejectReceive";
                setViewTextReceive();
                mCommonToolbar.getRightMenuView(0).setVisibility(View.INVISIBLE);
                break;
        }

        tvLot.setText(mReceiveBean.getLot());
        tvProductname.setText(mReceiveBean.getProductName());
        tvProductSpec.setText(mReceiveBean.getProductSpec());

        tvPackageNum.setText(mReceiveBean.getReceivePackageNum().toString());// 到货包数
        tvReceiveNum.setText(mReceiveBean.getQtyArrived().toString() + mReceiveBean.getUomName());//到货数量
        //拒收数量、拒收包数
        tvRejectedNum.setText(mReceiveBean.getQtyRejected().toString() + mReceiveBean.getUomName());
        tvRejectedPackageNum.setText(mReceiveBean.getRejectedReceivePackageNum().toString());


    }

    //验收场合控件显示
    private void setViewTextReceive() {
        waitReceiveNum = mReceiveBean.getQtyCheckLeft();
        //设置待验收包数
        tvWaitPackageNum.setText(mReceiveBean.getPackageCountCheckLeft().toString());//待收包数
        tvWaitReceiveNum.setText(mReceiveBean.getQtyCheckLeft().toString() + mReceiveBean.getUomName());//待收数量
        //设置已验收包数
        tvReceivedPackageNum.setText(mReceiveBean.getPackageCountChecked().toString());//已收包数(已验收包数)
        tvReceivedNum.setText(mReceiveBean.getQtyChecked().toString() + mReceiveBean.getUomName());//已收数量(已验收数量)
    }

    //上架场合控件显示
    private void setViewTextPickUp() {
        //变更标签名称
        lvWaitPackageNum.setText("待入包数: ");//
        lvWaitReceiveNum.setText("待入数量: ");//
        lvReceivedPackageNum.setText("已入包数: ");//
        lvReceivedNum.setText("已入数量: ");//
        waitReceiveNum = mReceiveBean.getQtyPutawayLeft();
        //设置待上架包数
        tvWaitPackageNum.setText(mReceiveBean.getPackageCountPutawayLeft().toString());//待收包数
        tvWaitReceiveNum.setText(mReceiveBean.getQtyPutawayLeft().toString() + mReceiveBean.getUomName());//待收数量
        //设置已上架包数
        tvReceivedPackageNum.setText(mReceiveBean.getPackageCountPutawayed().toString());//已收包数(已上架包数)
        tvReceivedNum.setText(mReceiveBean.getQtyPutawayed() + mReceiveBean.getUomName());//已收数量(已上架数量)
    }

    private void backEvent() {
        assert mPresenter != null;
        if (mPresenter.isError) {
            setFragmentResult(RESULT_OK, new Bundle());
        }
        pop();
    }

    PackageBean packageBean;

    private void checkPackageNo(String packageNo) {
        if (tlTabs.getSelectedTabPosition() != 1) {
            Objects.requireNonNull(tlTabs.getTabAt(1)).select();
        }

        packageBean = new PackageBean(packageNo);
        int itemPosition = unPackageBeans.indexOf(packageBean);
        if (itemPosition >= 0) {
            if (waitReceiveNum.intValue() <= 0) {
                String message = "<font color='#FF0000'><big>该任务要求的包装数量扫描完毕！</big></font><br/>(如需替换，请重新输入要替换的包装将该包装移除出已扫包装列表！)";
                new MaterialDialog.Builder(mContext)
                        .title("提示")
                        .content(Html.fromHtml(message))
                        .positiveText(Html.fromHtml("<big>确认</big>"))
                        .show();
                return;

            }
            packageBean = unPackageBeans.get(itemPosition);
            mReceiveBean.setUnitQty(packageBean.getUnitPackQty().toString());
            doneScanAdapter.addData(packageBean);
            unPackageBeans.remove(itemPosition);
            updateAddPackageInfo(false, BigDecimal.ONE);
            if(waitReceiveNum.intValue() == 0){
                String message = "<font color='#FF0000'>该任务要求的包装数量扫描完毕，是否确认收货！</font>";
                MaterialDialog materialDialog =  new MaterialDialog.Builder(mContext)
                        .title("确认收货")
                        .content(Html.fromHtml(message))
                        .positiveText("是")
                        .negativeText("否")
                        .onPositive((dialog, which) -> {
                            btOk.performClick();
                        })
                        .build();
                materialDialog.getActionButton(DialogAction.POSITIVE).setTextSize(18);
                materialDialog.getActionButton(DialogAction.NEGATIVE).setTextSize(18);
                materialDialog.show();
            }
        } else if ((itemPosition = donePackageBeans.indexOf(packageBean)) >= 0) {
            final int i = itemPosition;
            new MaterialDialog.Builder(mContext)
                    .content("该包装已扫过，是否删除改包装？")
                    .positiveText("否")
                    .negativeText("是")
                    .onNegative((dialog, which) -> {
                        packageBean = donePackageBeans.get(i);
                        unScanAdapter.addData(packageBean);
                        doneScanAdapter.remove(i);
                        updateSubstractPackageInfo(BigDecimal.ONE);
                    }).show();
        } else {
            DialogUtil.showErrorDialog(mContext, "该包装不是未扫包装");
        }
    }

    /**
     * 增加包装
     */
    @SuppressLint("SetTextI18n")
    private void updateAddPackageInfo(boolean isReject, BigDecimal total) {
        switch (type) {
            case PURCHASE_CHECK:
                addQtyReceive(isReject,total);
                break;
            case PURCHASE_RECEIVE:
                addQtyPickUp(isReject,total);
                break;
            case YN_CHECK:
                addQtyReceive(isReject,total);
                break;
            case YN_RECEIVE:
                addQtyPickUp(isReject,total);
                break;
            case REJECT:
                addQtyReceive(isReject,total);
                break;
        }
    }

    //验收场合控件显示
    private void addQtyReceive(boolean isReject,BigDecimal total) {
        //当前包装的数量（当前选择的包装数量）
        BigDecimal multiply = total.multiply(new BigDecimal(mReceiveBean.getUnitQty()));

        //判断是正常扫码or拒收
        if (isReject) {
            //设置拒收数量
            mReceiveBean.setQtyRejected(mReceiveBean.getQtyRejected().add(multiply));
            mReceiveBean.setPackageCountRejected(mReceiveBean.getPackageCountRejected().add(total));
            tvRejectedNum.setText(mReceiveBean.getQtyRejected().toString()+mReceiveBean.getUomName());
            tvRejectedPackageNum.setText(mReceiveBean.getPackageCountRejected().toString());

            //设置已验收包数和数量
            mReceiveBean.setPackageCountChecked(mReceiveBean.getPackageCountChecked().subtract(total));
            mReceiveBean.setQtyChecked(mReceiveBean.getQtyChecked().subtract(multiply));// 已收数量
            tvReceivedPackageNum.setText(mReceiveBean.getPackageCountChecked().toString());//已收包数(已验收包数)
            tvReceivedNum.setText(mReceiveBean.getQtyChecked().toString() + mReceiveBean.getUomName());//已收数量(已验收数量)
        }else {
            waitReceiveNum = mReceiveBean.getQtyCheckLeft();
            //设置待验收包数和数量
            mReceiveBean.setPackageCountCheckLeft(mReceiveBean.getPackageCountCheckLeft().subtract(total));
            mReceiveBean.setQtyCheckLeft(mReceiveBean.getQtyCheckLeft().subtract(multiply));//待收数量
            tvWaitPackageNum.setText(mReceiveBean.getPackageCountCheckLeft().toString());//待收包数
            tvWaitReceiveNum.setText(mReceiveBean.getQtyCheckLeft().toString() + mReceiveBean.getUomName());//待收数量

            //设置已验收包数和数量
            mReceiveBean.setPackageCountChecked(mReceiveBean.getPackageCountChecked().add(total));
            mReceiveBean.setQtyChecked(mReceiveBean.getQtyChecked().add(multiply));// 已收数量
            tvReceivedPackageNum.setText(mReceiveBean.getPackageCountChecked().toString());//已收包数(已验收包数)
            tvReceivedNum.setText(mReceiveBean.getQtyChecked().toString() + mReceiveBean.getUomName());//已收数量(已验收数量)
        }
    }

    //上架场合控件显示
    private void addQtyPickUp(boolean isReject,BigDecimal total) {
        //当前包装的数量（当前选择的包装数量）
        BigDecimal multiply = total.multiply(new BigDecimal(mReceiveBean.getUnitQty()));

        //判断是正常扫码or拒收
        if (isReject) {
            //设置已上架包数和数量
            mReceiveBean.setPackageCountPutawayed(mReceiveBean.getPackageCountPutawayed().subtract(total));
            mReceiveBean.setQtyPutawayed(mReceiveBean.getQtyPutawayed().subtract(multiply));// 已收数量
            tvReceivedPackageNum.setText(mReceiveBean.getPackageCountPutawayed().toString());
            tvReceivedNum.setText(mReceiveBean.getQtyPutawayed().toString() + mReceiveBean.getUomName());
        }else {
            waitReceiveNum = mReceiveBean.getQtyPutawayLeft();
            //设置待上架包数和数量
            mReceiveBean.setPackageCountPutawayLeft(mReceiveBean.getPackageCountPutawayLeft().subtract(total));
            mReceiveBean.setQtyPutawayLeft(mReceiveBean.getQtyPutawayLeft().subtract(multiply));//待收数量
            tvWaitPackageNum.setText(mReceiveBean.getPackageCountPutawayLeft().toString());//待上架包数
            tvWaitReceiveNum.setText(mReceiveBean.getQtyPutawayLeft() + mReceiveBean.getUomName());//待收数量

            //设置已上架包数和数量
            mReceiveBean.setPackageCountPutawayed(mReceiveBean.getPackageCountPutawayed().add(total));
            mReceiveBean.setQtyPutawayed(mReceiveBean.getQtyPutawayed().add(multiply));// 已收数量
            tvReceivedPackageNum.setText(mReceiveBean.getPackageCountPutawayed().toString());
            tvReceivedNum.setText(mReceiveBean.getQtyPutawayed().toString() + mReceiveBean.getUomName());
        }
    }

    /**
     * 移除包装
     */
    @SuppressLint("SetTextI18n")
    private void updateSubstractPackageInfo(BigDecimal total) {
        switch (type) {
            case PR:
                subtractQtyReceive(total);
                break;
            case PURCHASE_RECEIVE:
                subtractQtyPickUp(total);
                break;
            case YN_CHECK:
                subtractQtyReceive(total);
                break;
            case YN_RECEIVE:
                subtractQtyPickUp(total);
                break;
            case REJECT:
                subtractQtyReceive(total);
                break;
        }
    }

    //验收场合控件显示
    private void subtractQtyReceive(BigDecimal total) {
        //当前包装的数量（当前选择的包装数量）
        BigDecimal multiply = total.multiply(new BigDecimal(mReceiveBean.getUnitQty()));

        //设置待验收包数和数量
        mReceiveBean.setPackageCountCheckLeft(mReceiveBean.getPackageCountCheckLeft().add(total));//已收包数
        mReceiveBean.setQtyCheckLeft(mReceiveBean.getQtyCheckLeft().add(multiply));// 已收数量
        tvWaitPackageNum.setText(mReceiveBean.getPackageCountCheckLeft().toString());//待收包数
        tvWaitReceiveNum.setText(mReceiveBean.getQtyCheckLeft().toString() + mReceiveBean.getUomName());//待收数量
        waitReceiveNum = mReceiveBean.getQtyCheckLeft();
        //设置已验收包数和数量
        mReceiveBean.setPackageCountChecked(mReceiveBean.getPackageCountChecked().subtract(total));
        mReceiveBean.setQtyChecked(mReceiveBean.getQtyChecked().subtract(multiply));//待收数量
        tvReceivedPackageNum.setText(mReceiveBean.getPackageCountChecked().toString());//已收包数(已验收包数)
        tvReceivedNum.setText(mReceiveBean.getQtyChecked().toString() + mReceiveBean.getUomName());//已收数量(已验收数量)
    }

    //上架场合控件显示
    private void subtractQtyPickUp(BigDecimal total) {
        //当前包装的数量（当前选择的包装数量）
        BigDecimal multiply = total.multiply(new BigDecimal(mReceiveBean.getUnitQty()));
        //设置待上架包数和数量
        mReceiveBean.setPackageCountPutawayLeft(mReceiveBean.getPackageCountPutawayLeft().add(total));
        mReceiveBean.setQtyPutawayLeft(mReceiveBean.getQtyPutawayLeft().add(multiply));//待收数量
        tvWaitPackageNum.setText(mReceiveBean.getPackageCountPutawayLeft().toString());//待收包数
        tvWaitReceiveNum.setText(mReceiveBean.getQtyPutawayLeft() + mReceiveBean.getUomName());//待收数量
        waitReceiveNum = mReceiveBean.getQtyPutawayLeft();
        //设置已上架包数和数量
        mReceiveBean.setPackageCountPutawayed(mReceiveBean.getPackageCountPutawayed().subtract(total));//已收包数
        mReceiveBean.setQtyPutawayed(mReceiveBean.getQtyPutawayed().subtract(multiply));// 已收数量
        tvReceivedPackageNum.setText(mReceiveBean.getPackageCountPutawayed().toString());
        tvReceivedNum.setText(mReceiveBean.getQtyPutawayed().toString() + mReceiveBean.getUomName());
    }

    private void initUnScanRecyclerView() {
        unScanAdapter = new PackageScanAdapter(unPackageBeans);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        unScanAdapter.setOnItemClickListener((adapter, view, position) -> {
            unScanAdapter.notifyItemChanged(unScanAdapter.getthisPosition());
            unScanAdapter.setThisPosition(position);
            ReceiveScanPackageFragment.this.position = position;
            PackageBean packageBean = (PackageBean) adapter.getData().get(position);
            tietNo.setText(packageBean.getPackageNo());
            unScanAdapter.notifyItemChanged(unScanAdapter.getthisPosition());
        });
        mRecyclerView.setAdapter(unScanAdapter);

    }

    private void initDoneScanRecyclerView() {
        doneScanAdapter = new PackageScanAdapter(donePackageBeans);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        doneScanAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            int itemClickPosition = -1;

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (itemClickPosition >= 0) {
                    doneScanAdapter.notifyItemChanged(itemClickPosition);
                    doneScanAdapter.setThisPosition(position);
                    itemClickPosition = position;
                    doneScanAdapter.notifyItemChanged(doneScanAdapter.getthisPosition());
                    // PackageBean packageBean= (PackageBean) adapter.getData().get(position);

                }
            }
        });
    }

    private void initEvent() {
        imgScan.setOnClickListener(v->{
            initZxing();
        });
        tietNo.setOnEditorActionListener((v,id,event)->{

            if ((id == KeyEvent.KEYCODE_CALL||id == KeyEvent.KEYCODE_UNKNOWN) && !tietNo.getText().toString().isEmpty()) {
                onBarcodeEventSuccess(tietNo.getText().toString());
            }
            return true;
        });
        tlTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        mRecyclerView.setAdapter(unScanAdapter);
                        break;
                    case 1:
                        mRecyclerView.setAdapter(doneScanAdapter);
                        break;
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    //获取待扫列表
    private void getData(String packageType) {
        JSONObject data = new JSONObject();

        /*page:'receive',showScaned:'Y',asnId:'121212'*/
        data.put("page", page);
        data.put("showScaned", packageType);
        data.put("asnId", mReceiveBean.getAsnId());
        data.put("asnLineId", mReceiveBean.getAsnLineId());
        assert mPresenter != null;
        mPresenter.queryAsnPackageDetail(data, list -> {
            if ("Y".equals(packageType)) {
                donePackageBeans = list;
            } else {
                unPackageBeans = list;
                initUnScanRecyclerView();
            }
        });

    }

    //
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initSpinner();
        initEvent();
        initDoneScanRecyclerView();
    }

    //货位选择框初始事件
    private void initSpinner() {
        spinnerLocator.setImageOnClickListener(new View.OnClickListener() {
            int i = 0;

            @Override
            public void onClick(View v) {
                if (i == 0) {
                    i++;
                    JSONObject data = new JSONObject();
                    data.put("productId", mReceiveBean.getProductId());
                    data.put("showStorageLoc", "");
                    mPresenter.getLocators(data, list -> {
                        locators = list;
                        locator = locators.get(0);
                        spinnerLocator.setItemData(locators);
                        spinnerLocator.setOnItemClickListener((parent, view, position, id) -> {
                            if (position >= 0) {
                                locator = spinnerLocator.getSelectItem();
                            }
                        });
                        v.performClick();
                    });
                }
            }
        });
        JSONObject data = new JSONObject();
        data.put("productId", mReceiveBean.getProductId());
//        data.put("showBigLoc", "Y");
        if (mReceiveBean.getLPackageQty() > 0) {
            data.put("unitPackQty", mReceiveBean.getLPackageQty());
        }
        assert mPresenter != null;
        mPresenter.getLocators(data, list -> {
            if (list.size() > 0) {
                locator = list.get(0);
                spinnerLocator.setText(locator.getName());
            }
        });

    }

    //标题栏设置与事件控制（拒收）
    protected void initToolBar(View rootView) {

        mCommonToolbar = rootView.findViewById(R.id.common_toolbar);
        TypedValue typedValue = new TypedValue();
        getActivity().getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
        mCommonToolbar.setBackgroundColor(typedValue.data);
        HomeItem item = _mActivity.getIntent().getParcelableExtra(DataKeys.HOME_ITEM.name());
        if(item != null && StringUtils.isNotBlank(item.getTitle())){
            mCommonToolbar.setTitleText(item.getTitle());
        }
        mCommonToolbar.addRightMenuText(TextViewOptions.Builder()
                .setText("拒收")
                .setLines(2)
                .setListener(v -> {
                    HttpClientHelper.showWareSelect(mContext, (dialog, itemView, which, text) -> {
                        ((TextView) v).setText(text);
                        return false;
                    });
                })
                .build());

        switch (type) {
            case PURCHASE_RECEIVE:
                mCommonToolbar.<TextView>getRightMenuView(0).setText("退回");
                break;
        }
        mCommonToolbar.<TextView>getRightMenuView(0).setOnClickListener(l -> {
            if (donePackageBeans.size() > 0) {
                assert mPresenter != null;
                JSONObject data = new JSONObject();
                if ("Y".equals(mReceiveBean.getIsControlledProduct())) {
                    OldReceiveFragment oldReceiveFragment = (OldReceiveFragment) getPreFragment();
                    if (oldReceiveFragment != null && oldReceiveFragment.getUser() == null) {
                        HttpClientHelper.showSelectSecondChangeDialog(getActivity(), (dialog, user) -> {
                            oldReceiveFragment.setUser(user);
                            data.put("workerId2", oldReceiveFragment.getUser().getId());
                            doRejectConfirm(data);
                        });
                        return;
                    }
                    data.put("workerId2", oldReceiveFragment.getUser().getId());
                }
                doRejectConfirm(data);
            } else {
                DialogUtil.showErrorDialog(mContext, "请选择拒收包装");
            }
        });
    }

    //拒收（退回）方法调用
    private void doRejectConfirm(JSONObject data) {
        switch (type) {
            case PR:
                doRejectConfirmReceive(data);
                break;
            case PURCHASE_RECEIVE:
                doRejectConfirmPickUp(data);
                break;
            case PURCHASE_CHECK:
                doRejectConfirmReceive(data);
                break;
            case YN_CHECK:
                doRejectConfirmReceive(data);
                break;
            case YN_RECEIVE:
                doRejectConfirmPickUp(data);
                break;
            case REJECT:
                doRejectConfirmReceive(data);
                break;
        }
    }

    //验收场合拒收方法调用
    private void doRejectConfirmReceive(JSONObject data) {
        mPresenter.queryListData(new Consumer<List<Statu>>() {
            int i = 0;
            @Override
            public void accept(List<Statu> status) throws Exception {
                new MaterialDialog.Builder(mContext)
                        .title("拒收原因")
                        .items(status)
                        .itemsCallbackSingleChoice(i, (dialog, itemView, which, text) -> {
                            i = which;
                            // {asnId:"1212",asnLineId:12123,rejectReason:"test",packageNo:["2323","232323dfdf"]}}
                            // JSONObject data = new JSONObject();
                            data.put("asnId", mReceiveBean.getAsnId());//
                            data.put("asnLineId", mReceiveBean.getAsnLineId());
                            data.put("rejectReason", status.get(i).getId());
                            JSONArray packageNos = new JSONArray();
                            for (PackageBean p : donePackageBeans) {
                                packageNos.add(p.getPackageNo());
                            }
                            data.put("packageNo", packageNos);
                            mPresenter.rejectAsnPackage(data, () -> {
                                showMessage("处理成功！");

                                if(unScanAdapter.getData().size() == 0 ){
                                    setFragmentResult(RESULT_OK,new Bundle());
                                    pop();
                                }else{
                                    for(PackageBean p: doneScanAdapter.getData()){
                                        packageBean = p;
                                        mReceiveBean.setUnitQty(packageBean.getUnitPackQty().toString());
                                        updateAddPackageInfo(true,BigDecimal.ONE);
                                    }
                                    doneScanAdapter.getData().clear();
                                    doneScanAdapter.notifyDataSetChanged();
//                                            BigDecimal rejectPackageNum = new BigDecimal(donePackageBeans.size());
//                                            doneScanAdapter.getData().clear();
//                                            doneScanAdapter.notifyDataSetChanged();
//                                            updateAddPackageInfo(true, rejectPackageNum);
                                }
                            });
                            return true;
                        }).neutralText("取消")
                        .positiveText("确认")
                        .build()
                        .show();
            }
        });
    }

    ///上架场合退回方法调用
    private void doRejectConfirmPickUp(JSONObject data) {
        data.put("asnId", mReceiveBean.getAsnId());//
        data.put("asnLineId", mReceiveBean.getAsnLineId());
        JSONArray packageNos = new JSONArray();
        for (PackageBean p : donePackageBeans) {
            packageNos.add(p.getPackageNo());
        }
        data.put("packageNo", packageNos);

        assert mPresenter != null;
        mPresenter.pickbackAsnPackageRecieve(data, () -> {
            if (unPackageBeans.size() == 0) {
                showMessage("处理成功");
                setFragmentResult(RESULT_OK, new Bundle());
                pop();
            } else {
                new MaterialDialog.Builder(mContext)
                        .content("任务还没完成，是否继续？")
                        .neutralText("是")
                        .positiveText("否")
                        .onNeutral((dialog, which) -> {
                            donePackageBeans.clear();
                            doneScanAdapter.notifyDataSetChanged();
                        })
                        .onPositive((dialog, which) -> {
                            setFragmentResult(-3,null);
                            pop();
                        }).show();
            }

        });
    }

    //确认按钮按下事件
    @OnClick(R.id.bt_receive_scan_ok)
    public void onViewClicked() {
        if (donePackageBeans.size() > 0) {
            if (locator == null ) {
                DialogUtil.showErrorDialog(mContext, "请输入货位");
                return;
            }
            if("Y".equals(mReceiveBean.getIsNeerGuarantee())){
                new MaterialDialog.Builder(mContext)
                        .title("提示")
                        .content(mReceiveBean.getError()+",是否继续")
                        .positiveText("是")
                        .negativeText("否")
                        .onPositive((dialog, which) -> {
                            confirm();
                        }).show();
            }else{
                confirm();
            }
        } else {
            DialogUtil.showErrorDialog(mContext, "请扫码需要操作的包装后，在点击确认！");
        }
    }

    //验收确认
    private void confirm() {
        JSONObject data = new JSONObject();
        data.put("asnId", mReceiveBean.getAsnId());//
        data.put("asnLineId", mReceiveBean.getAsnLineId());
        data.put("locatorId", locator.getLocatorId());
        if ("Y".equals(mReceiveBean.getIsControlledProduct())) {

            OldReceiveFragment oldReceiveFragment = (OldReceiveFragment) getPreFragment();
            if (oldReceiveFragment != null && oldReceiveFragment.getUser() == null) {
                HttpClientHelper.showSelectSecondChangeDialog(getActivity(), (dialog, user) -> {
                    oldReceiveFragment.setUser(user);
                    data.put("workerId2", oldReceiveFragment.getUser().getId());
                    doConfirm(data);
                });
                return;
            } else {
                data.put("workerId2", oldReceiveFragment.getUser().getId());
            }
        }
        doConfirm(data);
    }

    //确认方法调用
    private void doConfirm(JSONObject data) {
        JSONArray packageNos = new JSONArray();
        for (PackageBean p : donePackageBeans) {
            packageNos.add(p.getPackageNo());
        }

        data.put("packageNo", packageNos);
        // {asnId:"1212",asnLineId:12123,locatorId:"1212",packageNo:["2323","232323dfdf"]}
        assert mPresenter != null;
        switch (type) {
            case PURCHASE_CHECK:
                doConfirmReceive(data);
                break;
            case PURCHASE_RECEIVE:
                doConfirmPickUp(data);
                break;
            case YN_CHECK:
                doConfirmReceive(data);
                break;
            case YN_RECEIVE:
                doConfirmPickUp(data);
                break;
            case REJECT:
                if(tvWaitPackageNum.getText().equals("0")){
                    doConfirmReject(data);
                }else{
                    DialogUtil.showErrorDialog(mContext,"待验收包数必须为零！");
                }
                break;
        }
    }

    //验收确认方法调用
    private void doConfirmReceive(JSONObject data) {
        mPresenter.checkAsnPackageRecieve(data, () -> {
            if (unPackageBeans.size() == 0) {
                showMessage("处理成功");
                setFragmentResult(RESULT_OK, new Bundle());
                pop();
            } else {
                new MaterialDialog.Builder(mContext)
                        .content("任务还没完成，是否继续？")
                        .neutralText("是")
                        .positiveText("否")
                        .onNeutral((dialog, which) -> {
                            donePackageBeans.clear();
                            doneScanAdapter.notifyDataSetChanged();
                        })
                        .onPositive((dialog, which) -> {
                            setFragmentResult(-3,null);
                            pop();
                        }).show();
            }
        });
    }

    //上架确认方法调用
    private void doConfirmPickUp(JSONObject data) {
        mPresenter.pickupAsnPackageRecieve(data, () -> {
            if (unPackageBeans.size() == 0) {
                showMessage("处理成功");
                setFragmentResult(RESULT_OK, new Bundle());
                pop();
            } else {
                new MaterialDialog.Builder(mContext)
                        .content("任务还没完成，是否继续？")
                        .neutralText("是")
                        .positiveText("否")
                        .onNeutral((dialog, which) -> {
                            donePackageBeans.clear();
                            doneScanAdapter.notifyDataSetChanged();
                        })
                        .onPositive((dialog, which) -> {
                            setFragmentResult(-3,null);
                            pop();
                        }).show();
            }
        });
    }

    //开箱验视确认
    private void inspectePackageConfirm() {
        JSONObject data = new JSONObject();
        data.put("asnId", mReceiveBean.getAsnId());//
        data.put("asnLineId", mReceiveBean.getAsnLineId());
        inspecteConfirm(data);
    }

    //开箱验视确认方法调用
    private void inspecteConfirm(JSONObject data) {
        JSONArray packageNos = new JSONArray();
        for (PackageBean p : donePackageBeans) {
            packageNos.add(p.getPackageNo());
        }

        data.put("packageNo", packageNos);
        // {asnId:"1212",asnLineId:12123,locatorId:"1212",packageNo:["2323","232323dfdf"]}
        assert mPresenter != null;
        mPresenter.inspectePackageRecieve(data, () -> {
            showMessage("验视处理成功");
        });
    }
    //取消上架
    private void doConfirmReject(JSONObject data) {
        mPresenter.rejectReceivePackage(data, () -> {
            if (unPackageBeans.size() == 0) {
                showMessage("处理成功");
                setFragmentResult(RESULT_OK, new Bundle());
                pop();
            } else {
                new MaterialDialog.Builder(mContext)
                        .content("任务还没完成，是否继续？")
                        .neutralText("是")
                        .positiveText("否")
                        .onNeutral((dialog, which) -> {
                            donePackageBeans.clear();
                            doneScanAdapter.notifyDataSetChanged();
                        })
                        .onPositive((dialog, which) -> {
                            setFragmentResult(-3,null);
                            pop();
                        }).show();
            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        unScanAdapter = null;
        doneScanAdapter = null;
        mRecyclerView = null;

    }

    //键盘上返回操作
    @Override
    public boolean onBackPressedSupport() {
        mCommonToolbar.getLeftMenuView(0).performClick();
        return true;
    }
}
